package com.xiaok.netty.client.channelInitializer;

import com.xiaok.common.protobuf.Message;
import com.xiaok.netty.client.handle.HeartHandler;
import com.xiaok.netty.client.handle.LogicClientHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

/**
 * @Classname ClientChannelInitializer
 * @Description 客户端 channelHandle 初始化类
 * @Date 2020/10/8 17:32
 * @Created by xiaok
 */
@Component(value = "clientChannelInitializer")
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${server.reader_idle_time_seconds}")
    private Integer readerIdleTimeSeconds;
    @Value("${server.writer_idle_time_seconds}")
    private Integer writerIdleTimeSeconds;
    @Value("${server.all_idle_time_seconds}")
    private Integer allIdleTimeSeconds;

    @Autowired
    @Qualifier("logicClientHandler")
    private ChannelInboundHandlerAdapter logicClientHandler;

    @Autowired
    @Qualifier("heartHandler")
    private ChannelInboundHandlerAdapter heartHandler;
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds
                , writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS));


        //解码器必须放在前面，否则发数据收不到
        pipeline.addLast(new ProtobufVarint32FrameDecoder());//添加protobuff解码器
        pipeline.addLast(new ProtobufDecoder(Message.MessageBase.getDefaultInstance()));//添加protobuff对应类解码器
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());//protobuf的编码器 和上面对对应
        pipeline.addLast(new ProtobufEncoder());//protobuf的编码器

        pipeline.addLast("clientHandler", logicClientHandler);
        pipeline.addLast("idleTimeoutHandler", heartHandler);

    }
}
